﻿@{
    ViewBag.Title = "统计台帐";
    Layout = "~/Views/Shared/_ManufactureList.cshtml";
}
<link href="~/Content/css/statistic_ledger.css" rel="stylesheet" />
<link href="~/Content/css/statistic_ledger_print.css" rel="stylesheet" media="print" />
<script type="text/javascript">
    $(function () {
        Index.init();
    });

    var Index = {
        productUnits:@Html.Raw(ViewData["productUnitList"].ToString()),
        sparePartsLists:@Html.Raw(ViewData["sparePartsList"].ToString()),
        defaultDate:@Html.Raw(ViewData["LedgerDate"].ToString()),
        curUnit:'@ViewData["curUnit"].ToString()',
        curUserName:'@ViewData["curUserName"].ToString()',
        curDate:'@ViewData["curDate"].ToString()',
        curTime:'@ViewData["curTime"].ToString()', 
        UseUnit:'25000',
        printItemTemplate:"",
        dataList:null,
        init: function () {
            with (Index) {
                printItemTemplate = $("#print .page").html();

                initControl();

                initDicData();

                with(Index){
                    loadData(function(data){
                        var columnInfo = [
                                { caption: '零件编号', name: 'FProductionNO'},
                                { caption: '零件名称', name: 'FProductionName'},
                                { caption: "即时库存", name: "FImmeQuantity" },
                                { caption: '账面库存', name: 'FBookQuantity'},
                                { caption: '安全储备', name: 'FSafetystore'},
                                { caption: '最高储备', name: 'FHighestStore'},
                                { caption: '最低储备', name: 'FLowestStore'},
                                { caption: '日均消耗', name: 'FDailyConsume'},
                                { caption: '单价 （元）', name: 'Fprice_X'},
                                { caption: '账面金额（元）', name: 'FBookMoney'},
                                { caption: '制造单位名称', name: 'FProCompanyName'},
                                { caption: '零件分类', name: 'FProductionTypeName'}
                        ];

                        dataList = data.rows;
                        
                        renderPrintData($("#print"),data.rows,columnInfo);
                    });
                }
            }
        },
        initControl: function () {
            $("#txtDate").val(Index.defaultDate);

            var tmp = new Date().format("yyyyMM"),date="";

            date={year:tmp.substr(0,4),month:tmp.substr(4,2)};

            $("h1").text("{year}年{month}月零部件库存目录".format(date));

            $("#txtDate").on("change",function(){
                Index.defaultDate = $(this).val();
            });

            $("[date-control]").on("click", function () {
                WdatePicker({ dateFmt: 'yyyyMM', minDate: '2000-1', maxDate: '2050-12' });
            });

            $("#gridList").delegate("a[明细账页]","click",function(){
                var num = $.trim($(this).parents("tr").attr("id"));

                r = Index.dataList[num-1];

                var o = {
                    "制造单位":r["FProCompanyNO"],
                    "制造单位名称":r["FProCompanyName"],
                    "分类编号":r["FProductionTypeNO"],
                    "零件分类":r["FProductionTypeName"],
                    "零件名称":r["FProductionName"],
                    "零件编号":r["FProductionNO"],
                    "单价 （元）":r["Fprice_X"],
                    "最高储备":r["FHighestStore"],
                    "最低储备":r["FLowestStore"]
                };

                var jsonData = {param:JSON.stringify(o),FAccountDate:Index.defaultDate};
                
                var url = "/WareHouse/EnterWareHouse/WareHouseLedgerDetails?{0}".format($.param(jsonData));

                location.href = url;
            });
            
            $("#gridList").delegate("a[统计台账]","click",function(){
                var num = $.trim($(this).parents("tr").find("td:first").text());

                var r = $.grep(Index.dataList,function(n,i){
                    return n["num"] == num;
                });

                var o = {
                    "制造单位":r[0]["FProCompanyNO"],
                    "制造单位名称":r[0]["FProCompanyName"],
                    "分类编号":r[0]["FProductionTypeNO"],
                    "零件分类":r[0]["FProductionTypeName"],
                    "零件名称":r[0]["FProductionName"],
                    "零件编号":r[0]["FProductionNO"],
                    "单价 （元）":r[0]["Fprice_X"],
                    "最高储备":r[0]["FHighestStore"],
                    "最低储备":r[0]["FLowestStore"]
                };

                var jsonData = {param:JSON.stringify(o),FAccountDate:Index.defaultDate};
                
                var url = "/WareHouse/EnterWareHouse/StatisticLedgerDetails?{0}".format($.param(jsonData));

                location.href = url;
            });

            $("#butnQuery").on("click", function () {
                var colNames = "pu,sp,no,name,date".split(",");

                var param = {};

                var $gridList = $("#gridList");

                colNames.forEach(function(cur){
                    param[cur] = $("[name={0}]".format(cur)).val();
                });
            
                param["isCurrent"] = (Index.defaultDate ==$("[name=date]").val()?"1":"0");

                $gridList.jqGrid('setGridParam', {
                    postData: {param:JSON.stringify(param)},
                }).trigger('reloadGrid');
            });

            $("#butnPrint").on("click",function(){
                var tmp = $("#txtDate").val(),date="";

                date={year:tmp.substr(0,4),month:tmp.substr(4,2)};

                $("h1").text("{year}年{month}月零部件库存目录".format(date));

                $("#print").jqprint();
            });

            $("#butnExportExcel").on("click",function(){
                var url = "/Common/ExcelExport?{0}".format($.param(Index.buildSql()));
      
                location.href=url;
            });
        },initDicData:function(){
            var pu = $("#selProductUnitList"),sp=$("#selSparePartsLists");
            
            Index.sparePartsLists.forEach(function(cur){
                $("<option value=\"{FTypeNO}\">{FTypeNO} {FTypeName}</option>".format(cur)).appendTo(sp);
            });

            Index.productUnits.forEach(function(cur){
                $("<option value=\"{UnitNO}\">{UnitNO} {UnitShortName}</option>".format(cur)).appendTo(pu);
            });
        },
        loadData:function(onLoadComplate){
            var colNames = "pu,sp,no,name,date".split(",");

            var param = {};

            colNames.forEach(function(cur){
                param[cur] = $("[name={0}]".format(cur)).val();
            });
            
            param["isCurrent"] = (Index.defaultDate ==$("[name=date]").val()?"1":"0");

            var $gridList = $("#gridList");
         
            $gridList.dataGridForJson({
                url: "/WareHouse/EnterWareHouse/GetStatisticLedgersJSONData",
                height: $(window).height() - 140,
                colModel: [
                { label: '操作', name: '操作', width: 180, align: 'center', frozen: true },
                { label: '零件编号', name: 'FProductionNO', width: 100, align: 'left', frozen: true },
                { label: '零件名称', name: 'FProductionName', width: 160, align: 'left', frozen: true },
                { label: "即时库存", name: "FImmeQuantity", width: 80, align: 'right' },
                { label: '账面库存', name: 'FBookQuantity', width: 80, align: 'right' },
                { label: '安全储备', name: 'FSafetystore', width: 80, align: 'right' },
                { label: '最高储备', name: 'FHighestStore', width: 80, align: 'right' },
                { label: '最低储备', name: 'FLowestStore',  width: 80, align: 'right' },
                { label: '日均消耗', name: 'FDailyConsume', width: 80, align: 'right' },
                { label: '单价 （元）', name: 'Fprice_X', formatter: 'number', width: 100, align: 'right' },
                { label: '账面金额（元）', name: 'FBookMoney', formatter: 'number', width: 100, align: 'right' },
                { label: '制造单位', name: 'FProCompanyNO', width: 100, align: 'center' },
                { label: '制造单位名称', name: 'FProCompanyName', width: 160, align: 'left' },
                { label: '分类编号', name: 'FProductionTypeNO', width: 80, align: 'center' },
                { label: '零件分类', name: 'FProductionTypeName', width: 120, align: 'center' },
                { label: '', name: '', width: $(window).width() - 1660, align: 'left' }
                ],
                postData:{param:JSON.stringify(param)},
                pager: "#gridPager",
                sortname: 'FProductionNO,FProductionName',
                sortorder:"asc",
                viewrecords: true,
                rownumWidth: 50,
                loadComplete: function (data) {  
                    onLoadComplate&&onLoadComplate(data);
                }  
            });
            
        },
        renderPrintData:function(c,data,colunmInfo){
            c.empty();
            
            var rows = 16;

            var max = data.length;
            
            var item = {page:1,maxPage:1,title:$("#wrapper h1").text() ,unit:Index.curUnit,user:Index.curUserName,date:Index.curDate,time:Index.curTime,table:null};

            var maxPage = Math.ceil(max/rows);

            item.maxPage = maxPage;

            for(var i = 0;i < maxPage;i++){
                var isFirst = true;

                var start = i*rows,end=(i+1)*rows;

                end>max && (end=max);

                var table = $("<table>"),pageItem = $("<div>").addClass("page");

                item.page = i+1;
                
                for(var j = start;j<end; j++){
                    var cur = data[j];

                    isFirst && (function(){
                        var title = $("<tr>");

                        for(var idx in colunmInfo){
                            $("<th>").text(colunmInfo[idx].caption).appendTo(title);
                        }

                        title.appendTo(table);

                        isFirst = false;
                    })();

                    !isFirst && (function(){
                        var row = $("<tr>");

                        for(var idx in colunmInfo){
                            $("<td>").text(cur[colunmInfo[idx].name]).appendTo(row);
                        }

                        row.appendTo(table);
                    })();
                }
                
                item.table = "<table>{0}</table>".format(table.html());

                pageItem.html(Index.printItemTemplate.format(item)).appendTo(c);
            }
        },
        buildSql:function(){
            var colNames = "pu,sp,no,name,date".split(",");

            var parames = {},con="";

            colNames.forEach(function(cur){
                parames[cur] = $("[name={0}]".format(cur)).val();
            });
                
            parames["isCurrent"] = (Index.defaultDate ==$("[name=date]").val()?"1":"0");

            var param = {sql:""};

            param.sql = sql = " SELECT                 FProductionNO 零件编号,                 FProductionName 零件名称,                 FImmeQuantity 即时库存,                 FBookQuantity 账面库存,                 FSafetystore 安全储备,                 FHighestStore 最高储备,                 FLowestStore 最低储备,                 FDailyConsume 日均消耗,                 Fprice_X \"单价 （元）\",                 FBookMoney \"账面金额（元）\",                 FProCompanyNO 制造单位,                 FProCompanyName 制造单位名称,                 FProductionTypeNO 分类编号,                 FProductionTypeName 零件分类                 FROM                 dbo.V_CPK_71_KC_StoCPKStockCata                 WHERE                 UseUnit = '{1}'                 AND FAccountDate = '{0}'                 {2}                 ORDER BY                 FProductionNO,                 FProductionName";
                
            "0"==parames["isCurrent"] &&  (sql = "SELECT                     FProductionNO 零件编号,                 FProductionName 零件名称,                 FImmeQuantity 即时库存,                 FBookQuantity 账面库存,                 FSafetystore 安全储备,                 FHighestStore 最高储备,                 FLowestStore 最低储备,                 FDailyConsume 日均消耗,                 Fprice_X \"单价 （元）\",                 FBookMoney \"账面金额（元）\",                 FProCompanyNO 制造单位,                 FProCompanyName 制造单位名称,                 FProductionTypeNO 分类编号,                 FProductionTypeName 零件分类                     FROM                     dbo.V_CPK_72_KC_StoCPKStockCata_Arc                     WHERE                     UseUnit = '{1}'                     AND FAccountDate = '{0}'                     {2}                     ORDER BY                     FProductionNO,                     FProductionName");
                
            ""!=parames["pu"] && (con+=" and FProCompanyNO = '{0}' ".format(parames["pu"]));

            ""!=parames["sp"] && (con+=" and FProductionTypeNO = '{0}' ".format(parames["sp"]));

            ""!=parames["no"] && (con+=" and FProductionNO = '{0}' ".format(parames["no"]));

            ""!=parames["name"] && (con+="  and FProductionName like '%{0}%'  ".format(parames["name"]));
                
            param.sql = param.sql.format(parames["date"], Index.curUnit, con);

            return param;
        }
    };

</script>
<body>
    <div id="wrapper">
        <h1>零部件库存目录</h1>
        <header>
            <div class="f_l">
                <div class="input_area">
                    <h2 class="input_title">台账日期</h2>
                    <div class="input_c  input_c_w12" style="width: 8.5em;">
                        <input id="txtDate" name="date" type="text" class="txt_common" date-control />
                       
                    </div>
                </div>
                <div class="input_area">
                    <h2 class="input_title">零件</h2>
                    <div class="input_c input_c_w12">
                        <input id="txtLedgerNo" name="no" type="text" class="txt_common" />
                    </div>
                </div>
                <div class="input_area input_c_w20 display_none">
                    <h2 class="input_title">零件名称</h2>
                    <div class="input_c">
                        <input id="txtLedgerName" name="name" type="text" class="txt_common" />
                    </div>
                </div>
                <div class="input_area">
                    <h2 class="input_title">制造单位</h2>
                    <div class="input_c input_c_w15">
                        <select id="selProductUnitList" name="pu" class="sel_common ">
                            <option value="">请选择</option>
                        </select>
                    </div>
                </div>
                <div class="input_area">
                    <h2 class="input_title">零件分类</h2>
                    <div class="input_c input_c_w12">
                        <select id="selSparePartsLists" name="sp" class="sel_common">
                            <option value="">请选择</option>
                        </select>
                    </div>
                </div>

            </div>
            <div class="f_r">
                <button id="butnQuery" class="butn_common">
                    <span class="glyphicon glyphicon-refresh"></span>查询
                </button>
                <button id="butnPrint" class="butn_common">
                    <span class="glyphicon glyphicon-print"></span>打印
                </button>
                <button id="butnExportExcel" class="butn_common">
                    <span class="glyphicon glyphicon-export"></span>导出
                </button>
            </div>
        </header>
        <div class="table_c">
            <table id="gridList"></table>
            <div id="gridPager"></div>
        </div>
        <!--<div class="table_c">
            <table id="dataList">
            </table>
        </div>
        <div class="page_view">
            <div class="page_total">显示第 1 - 1 条记录　检索到 1 条记录</div>
            <div class="pages">
                <a href="javascript:void(0);" class="page _bg_bg_page_01">首页</a>
                <a href="javascript:void(0);" class="page _bg_bg_page_02">上页</a>
                <input type="text" class="txt_page" value="1" />
                <div class="show_page">共一页</div>
                <a href="javascript:void(0);" class="page _bg_bg_page_03">下页</a>
                <a href="javascript:void(0);" class="page _bg_bg_page_04">末页</a>
                <select class="sel_page">
                    <option>50</option>
                    <option>150</option>
                    <option>200</option>
                </select>
            </div>
        </div>-->
    </div>
    <div id="print">
        <div class="page break_page">
            <h1>{title}</h1>
            <div class="top">
                单位：<div class="unit">{unit}</div>
                <div class="right_page">第{page}页，共{maxPage}页</div>
            </div>
            <div class="table_c">
                {table}
            </div>
            <footer>
                <span>打印人员：<label>{user}</label></span> <span>打印日期：<label>{date}</label><label>{time}</label></span>
            </footer>
        </div>
    </div>
</body>
